﻿using System;
using System.Collections.Generic;
using Core.Base.Module;
using Core.Extension;
using Core.Mgr;
using Core.Mgr._EventSys;
using Core.Mgr._Timer;
using UnityEngine;
using Core.Mgr.ABTest;
using Core.Mgr.Localize;
using Logic.Global;
using Model;
using QQSDK;
using UnityEngine.SceneManagement;


namespace Logic.Main
{
    public class AdMgr : Core.Extension.Singleton<AdMgr>
    {
        /// 是否展示Banner
        public bool IsShowBanner => ConfigMgr.Ins.ConfigModel.showBanner.Equals(1);

        /// <summary>
        /// 是否展示插屏
        /// </summary>
        public bool IsShowInter => ConfigMgr.Ins.ConfigModel.showInter.Equals(1);

        /// 是否展示激励
        public bool IsShowReward => ConfigMgr.Ins.ConfigModel.showReward.Equals(1);

        /// 上一次观看广告结束的时间
        public DateTime lastAdEndTime = DateTime.MinValue;

        /// 循环展示Banner的计时器 
        private int _timerIdLoopShowBanner = -1;

        /// <summary>
        /// 是否初始化过后置归因
        /// </summary>
        public bool IsInitedHouZhiGuiYin
        {
            get => PlayerPrefsX.GetBool("IsInitedHouZhiGuiYin", false);
            set => PlayerPrefsX.SetBool("IsInitedHouZhiGuiYin", value);
        }

        public void OnInit()
        {
            SDKManager.Init();
            InitAdsCallback();
            DaDianMgr.SetUserProperty("astc", SystemInfo.SupportsTextureFormat(TextureFormat.ASTC_4x4) ? 1 : -1, false);
            DaDianMgr.SetUserProperty("GraphicsDeviceType", SystemInfo.graphicsDeviceType.ToString(), true);
        }

        /// 是否正在展示Banner
        private bool BannerIsShowing { get; set; } = false;

        /// 展示Banner广告
        public void ShowBanner()
        {
            if (!IsShowBanner) return;
            if (BannerIsShowing) return;
            Debug.Log("ShowBanner");
            AdsManager.instance.ShowBanner(false);
        }

        /// 隐藏Banner
        public void HideBanner()
        {
            Debug.Log("HideBanner");
            AdsManager.instance.HideBanenr();
            BannerIsShowing = false;
        }

        private Action _openCb;
        private Action _closeCb;

        /// <summary>
        /// 插屏广告
        /// </summary>
        public void ShowInterstitial(Action showFailCb = null, Action openCb = null, Action closeCb = null,
            string position = "")
        {
            if (!IsShowInter)
            {
                showFailCb?.Invoke();
                return;
            }

            if ((DateTime.Now - lastAdEndTime).TotalSeconds < ConfigMgr.Ins.ConfigModel.interstitialAdInterval)
            {
                Debug.Log($"插屏播放失败，间隔小于{ConfigMgr.Ins.ConfigModel.interstitialAdInterval}S");
                showFailCb?.Invoke();
                DaDianMgr.Task("interstitial_location", "position", position, "error_code", 503);
                return;
            }

            _openCb = openCb;
            _closeCb = closeCb;
            _openCb += delegate { DaDianMgr.Task("interstitial_open", "position", position); };
            _closeCb += delegate { DaDianMgr.Task("interstitial_impression", "position", position); };
            DaDianMgr.Task("interstitial_trigger", "position", position);
            if (AdsManager.instance.IsAvailableInterstitial())
            {
                AdsManager.instance.ShowInterstitial(position);
                DaDianMgr.Task("interstitial_location", "position", position);
            }
            else
            {
                showFailCb?.Invoke();
                DaDianMgr.Task("interstitial_location", "position", position, "error_code", 302);
            }
        }

        private Action _onRewardOpenCb;
        private Action _onGetReward;

        /// 展示激励广告
        public void ShowRewardVideo(Action onGetReward, string position)
        {
            if (!IsShowReward)
            {
                onGetReward?.Invoke();
                return;
            }

            _onGetReward = onGetReward;
            _onRewardOpenCb = delegate { DaDianMgr.Show("reward_open", "position", position, "role"); };
            _onGetReward += delegate { DaDianMgr.Show("reward_impression", "position", position); };
            if (!_curRewardLocation.Remove(position)) Debug.LogError("错误！当前激励位没有进行Location登记！！！");
            DaDianMgr.Click("reward_trigger", "position", position);
            if (AdsManager.instance.IsAvailableRewardVideo())
            {
                AdsManager.instance.ShowRewardVideo(SceneManager.GetActiveScene().name);
            }
            else
            {
                Util.ShowTips(LocalizedMgr.Ins.GetLocalStr("ID_29"));
                DaDianMgr.Task("reward_error", "position", position);
                OnEnterRewardLocation(position);
            }
        }

        /// 当前正在展示中的激励位 
        private List<string> _curRewardLocation = new();

        /// <summary>
        /// 代表到达激励位的打点
        /// </summary>
        public void OnEnterRewardLocation(string position)
        {
            if (_curRewardLocation.Contains(position)) return; //当前类型的激励已经打过曝光了(reward_location)
            DaDianMgr.Task("reward_location", "position", position);
            _curRewardLocation.Add(position);
        }

        /// <summary>
        /// 当退出了激励位
        /// </summary>
        public void OnExitRewardLocation(string position)
        {
            if (!_curRewardLocation.Remove(position)) return;
            // 当前激励位直到退出也没有Trigger，算用户取消
            DaDianMgr.Task("reward_error", "position", position, "error_code", 505);
        }

        private void InitAdsCallback()
        {
            AdsManager.instance.onNativeLoaded += () => { Debug.Log("Native加载成功"); };
            AdsManager.instance.onNativeLoadedFailed += () => { Debug.Log("Native加载失败"); };
            AdsManager.instance.onNativeOpen += () => { Debug.Log("Native打开"); };
            AdsManager.instance.onNativeClick += () => { Debug.Log("Native点击"); };
            AdsManager.instance.onNativeClose += () => { Debug.Log("Native关闭"); };
            AdsManager.instance.onBannerLoadedFailed += () =>
            {
                BannerIsShowing = false;
                Debug.Log("Banner加载失败");
            };
            AdsManager.instance.onBannerImpression += () =>
            {
                BannerIsShowing = true;
                Debug.Log("banner展示成功");
                TimerMgr.EndTimer(_timerIdLoopShowBanner);
            };
            AdsManager.instance.onBannerClick += () => { Debug.Log("Banner点击"); };
            AdsManager.instance.onInterstitialOpen += () =>
            {
                // 插屏开启打点
                _openCb?.Invoke();
                _openCb = null;
                Debug.Log("Interstitial 打开");
            };
            AdsManager.instance.onInterstitialLoaded += () => { Debug.Log("Interstitial载入成功"); };
            AdsManager.instance.onInterstitialLoadedFailed += delegate { Debug.Log("Interstitial载入失败"); };
            AdsManager.instance.onInterstitialClose += () =>
            {
                // 插屏关闭打点
                _closeCb?.Invoke();
                _closeCb = null;
                Debug.Log("Interstitial 关闭");
                lastAdEndTime = DateTime.Now;
            };
            AdsManager.instance.onRewardOpen += () =>
            {
                Debug.Log("onRewardOpen");
                _onRewardOpenCb?.Invoke();
                _onRewardOpenCb = null;
            };
            AdsManager.instance.onRewardLoaded += () => { Debug.Log("onRewardLoaded"); };
            AdsManager.instance.onRewardComplete += () =>
            {
                if (!AppConst.IsGoogleAndroid || Application.isEditor)
                {
                    Debug.Log("onRewardComplete!!!");
                    _onGetReward?.Invoke();
                    _onGetReward = null;
                    lastAdEndTime = DateTime.Now;
                    GC.Collect();
                    EventMgr.Notify(E.OnExitRewardAd);
                }
            };
            AdsManager.instance.onUserRewarded += () =>
            {
                if (AppConst.IsGoogleAndroid && !Application.isEditor)
                {
                    Debug.Log("onRewardComplete!!!");
                    _onGetReward?.Invoke();
                    _onGetReward = null;
                    lastAdEndTime = DateTime.Now;
                    GC.Collect();
                    EventMgr.Notify(E.OnExitRewardAd);
                }
            };
            AdsManager.instance.onRewardLoadFialed += () => { Debug.Log("onRewardLoadFailed!!!"); };
            AdsManager.instance.onRewardInterrupt += () =>
            {
                Debug.Log("onRewardInterrupt!!!");
                EventMgr.Notify(E.OnExitRewardAd);
            };
            AdsManager.instance.onInitAdsSucceed += () =>
            {
                Debug.Log("onInitAdsSucceed!!!");
                _timerIdLoopShowBanner = TimerMgr.StartTimer(delegate
                {
                    Debug.Log("循环展示Banner");
                    ShowBanner();
                }, 0, -1, 5);
            };
        }
    }
}